package main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import main.util.RouterConfig;
import message.Router;

public class Main {

	private static final String FILE_SEPARATOR = File.separator;
	private static final String SEPARATOR = " ";
	private static Map<Integer, RouterConfig> routers;
	private static final String routersConfigFile = "config" + FILE_SEPARATOR + "roteador.config";
	private static final String linksConfigFile = "config" + FILE_SEPARATOR + "enlaces.config";
	private static int routersCount;
	
	// roteador.config
	// enlaces.config
	public static void main(String[] args) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		
		routers = new HashMap<Integer, RouterConfig>();
		configurateRouters(new File(routersConfigFile));
		configurateEnlaces(new File(linksConfigFile));
		
		System.out.print("Indique o identificador do roteador que você deseja iniciar: ");
		String input = reader.readLine();
		
		int initRouter = Integer.parseInt(input.trim());

		RouterConfig r_config = routers.get(initRouter);
		Router r = new Router(r_config, routersCount);
		r.start();
	}
	
	private static void configurateRouters(File configFile) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(configFile));
		
		String line = "";
		routersCount = 0;
		while ((line = reader.readLine()) != null) {
			routersCount++;
			
			String[] tokens = line.split(SEPARATOR);
			
			int routerId = Integer.parseInt(tokens[0]);
			int routerPort = Integer.parseInt(tokens[1]);
			String routerIp = tokens[2];
			
			RouterConfig router = new RouterConfig(routerId, routerPort, routerIp);
			routers.put(routerId, router);
		}
	}
	
	private static void configurateEnlaces(File configFile) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(configFile));
		
		String line = "";
		while ((line = reader.readLine()) != null) {
			String[] tokens = line.split(SEPARATOR);
			
			int router1Id = Integer.parseInt(tokens[0]);
			int router2Id = Integer.parseInt(tokens[1]);
			int distance = Integer.parseInt(tokens[2]);
			
			RouterConfig router1 = routers.get(router1Id);
			RouterConfig router2 = routers.get(router2Id);
			
			router1.addNeighbour(router2.getId(), router2.getPort(), router2.getIp(), distance);
			router2.addNeighbour(router1.getId(), router1.getPort(), router1.getIp(), distance);
		}
		
	}
}